var basePath = $("#basePath").val();
var userType = $("#userType").val();
$(document).ready(function (){
    menuCss("保养");
    initElementCss();
    initQueryTerm();
    queryUpkeepList(0,10);
    $("#show-count").change(function(){
        queryUpkeepList(0,$("#show-count").val());
    });
    bindEvent();
});

function bindEvent() {

    $("#emptyHospitalName").click(function (){
        $("#addUpkeepForm").find("[name='hospitalName']").val("");
        $("#addUpkeepForm").find("[name='hospitalId']").val("");
    });

    $("#emptyDeviceName").click(function (){
        $("#addUpkeepForm").find("[name='deviceName']").val("");
        $("#addUpkeepForm").find("[name='deviceId']").val("");
        $("#addUpkeepForm").find("[name='serviceType'][value='1103']").iCheck("check");
        $("#manufacturerDiv").find("[name='manufacturerName']").val("");
        $("#manufacturerDiv").find("[name='manufacturerId']").val("");
        $("#supplierDiv").find("[name='supplierName']").val("");
        $("#supplierDiv").find("[name='supplierId']").val("");
    });


    $("#addUpkeepForm").find("[name='serviceName']").typeahead (
        {
            source: function (query, process) {
                var url = basePath + "/base/queryHospitalMaintainer";
                var hospitalId =null;
                if(userType == 1104){
                    hospitalId = $("#addUpkeepForm").find("[name='hospitalId']").val();
                }else{
                    hospitalId = $("#hospitalId").val();
                }
                if(hospitalId == null || hospitalId=="" ){
                    return;
                }
                publicAjax(url,"POST",{hospitalId : hospitalId,name : query,serviceType:2902},function (data){
                    if(data.ret == 200){
                        if(data.data == null ||data.data.length == 0 ){
                            return process(new Array());
                        }
                        return  process(data.data);
                    }
                });

              /* var array = new  Array();
                array.push({serviceId:"123","name":"abc","serviceContacts":"刘晓","servicePhone":"13781332211"});
                array.push({serviceId:"456","name":"dbc","serviceContacts":"毛军","servicePhone":"12321123123"});
                process(array);*/

            }
            , updater: function (item) {
            $("#addUpkeepForm").find("[name='serviceId']").val(item.serviceId);
            $("#addUpkeepForm").find("[name='serviceContacts']").val(item.serviceContacts);
            $("#addUpkeepForm").find("[name='servicePhone']").val(item.servicePhone);
            return this.$element.val().replace(new RegExp(this.query + '$'),'') + item.name ;
        }

        });

    $("#assignMaintainerDiv").find("[name='serviceName']").typeahead ({
        source: function (query, process) {
            var url = basePath + "/base/queryMaintainerByCompletion";
            publicAjax(url,"POST",{keyword : query},function (data){
                if(data.ret == 200){
                    if(data.data == null ||data.data.length == 0 ){
                        return null;
                    }else{
                        var array = new Array();
                        $.each(data.data,function (index,item){
                            array.push({maintainerId:item.maintainerId,name:item.maintainerName,maintainerContacts:item.maintainerContacts,maintainerPhone:item.maintainerPhone});
                        });

                        return  process(array);
                    }
                }
            });
        },updater : function (item){
            $("#assignMaintainerDiv").find("[name='serviceId']").val(item.maintainerId);
            $("#assignMaintainerDiv").find("[name='serviceContacts']").val(item.maintainerContacts);
            $("#assignMaintainerDiv").find("[name='servicePhone']").val(item.maintainerPhone);
           return this.$element.val().replace(new RegExp(this.query + '$'),'') + item.name ;
        }
    });

    $("#device").click(function (){
        var hospitalId = $("#hospitalId").val();
        if(hospitalId == null || hospitalId == ""){
            hospitalId = $("#addUpkeepForm").find("[name='hospitalId']").val();
        }
        $("#deviceDvie").device({root:basePath,hospitalId:hospitalId,callback:function (data){
            var deviceName = data.deviceName;
            var lastUpkeepDate = data.lastUpkeepDate == null ? '暂无保养' : +data.lastUpkeepDate;
            $("#addUpkeepForm").find("[name='deviceId']").val(data.deviceId);
            $("#addUpkeepForm").find("[name='deviceName']").val(data.deviceName);
            $("#addUpkeepForm").find("[name='lastUpkeepDateSpan']").html(lastUpkeepDate);
            $("#addUpkeepForm").find("[name='hospitalId']").val(data.hospitalId);
            $("#addUpkeepForm").find("[name='hospitalName']").val(data.hospitalName);
            var urls = basePath + "/upkeep/queryDeviceIsUpkeep";//判断当前设备是否在保养中。如果在保养中给个提示。
            publicAjax(urls,"POST",{deviceId:data.deviceId},function (data){
                if(data.ret == 200){
                    if(data.data == 1){
                        deviceUpkeepPrompt(data.msg);
                    }
                }
            });

            var url = basePath + "/repair/queryInfoPage";
            publicAjax(url,"POST",{deviceId:data.deviceId},function (data){
                if(data.ret == 200){
                    if(data.data != null && data.data != ''){
                        if(data.data.manufacturer != null){
                            $("#manufacturerDiv").find("[name='manufacturerName']").val(data.data.manufacturer.manufacturerName);
                            $("#manufacturerDiv").find("[name='manufacturerId']").val(data.data.manufacturer.manufacturerId);
                            $("#manufacturerDiv").show();
                            $("#addUpkeepForm").find("[name='serviceType'][value='1102']").parent().parent().show();
                        }else{
                            $("#manufacturerDiv").hide();
                            $("#addUpkeepForm").find("[name='serviceType'][value='1102']").parent().parent().hide();
                        }
                        if(data.data.supplier != null){
                            $("#supplierDiv").find("[name='supplierName']").val(data.data.supplier.supplierName);
                            $("#supplierDiv").find("[name='supplierId']").val(data.data.supplier.supplierId);
                            $("#supplierDiv").show();
                            $("#addUpkeepForm").find("[name='serviceType'][value='1105']").parent().parent().show();
                        }else{
                            $("#supplierDiv").hide();
                            $("#addUpkeepForm").find("[name='serviceType'][value='1105']").parent().parent().hide();
                        }

                        if(data.data.serviceType == null){
                            $("#addUpkeepForm").find("[name='serviceType'][value='1103']").iCheck("check");
                        }else{
                            $("#addUpkeepForm").find("[name='serviceType'][value='"+data.data.serviceType+"']").iCheck("check");
                        }

                        if(data.data.serviceType == 1103){
                            $("#maintainerDiv").show();
                            $("#supplierDiv").hide();
                            $("#manufacturerDiv").hide();
                            $("#addUpkeepEngineerDiv").show();
                        }else if(data.data.serviceType == 1102){
                            $("#manufacturerDiv").show();
                            $("#maintainerDiv").hide();
                            $("#supplierDiv").hide();
                            $("#addUpkeepForm").find("[name='serviceId']").val(data.data.manufacturer.manufacturerId);
                            $("#addUpkeepEngineerDiv").show();
                        }else if(data.data.serviceType == 1105){
                            $("#manufacturerDiv").hide();
                            $("#maintainerDiv").hide();
                            $("#supplierDiv").show();
                            $("#addUpkeepForm").find("[name='serviceId']").val(data.data.supplier.supplierId);
                            $("#addUpkeepEngineerDiv").show();
                        }else{
                            $("#manufacturerDiv").hide();
                            $("#maintainerDiv").hide();
                            $("#supplierDiv").hide();
                            $("#maintainerDiv").show();
                        }

                    }else{
                        $("#addUpkeepForm").find("[name='serviceType'][value='1103']").iCheck("check");
                        $("#manufacturerDiv").find("[name='manufacturerName']").val("");
                        $("#manufacturerDiv").find("[name='manufacturerId']").val("");
                        $("#supplierDiv").find("[name='supplierName']").val("");
                        $("#supplierDiv").find("[name='supplierId']").val("");
                    }
                    serviceTypeChange();
                }else{
                    flavrShowByTime(data.msg,null,"danger",false);
                }
            });
        }});
    });

    $("#hospital").click(function (){
        var json = {};
        json.root = basePath;
        $("#hospitalDvie").hospital({root:basePath,callback:function (data){
            var hospital = data.getSelectedData();
            $("#addUpkeepForm").find("[name='hospitalId']").val(hospital.hospitalId);
            $("#addUpkeepForm").find("[name='hospitalName']").val(hospital.hospitalName);
        }});
    });

    $("#add").click(function (){
        if(userType == 1101){
           $("#addUpkeepForm").find("[name='upkeepApplicant']").val($("#realName").val());
            $("#addUpkeepForm").find("[name='upkeepApplicantPhone']").val($("#mobile").val());
        }

        $("#addUpkeep-modal").iziModal("open",this);
    });

    $("#saveUpkeep").click(function (){
        saveUpkeep();
    });

    $("#search").click(function (){
        queryUpkeepList(0,10);
    });

    $("#assign").click(function (){
        assignServiceInit();
    });

    $("#saveExamineMaintainer").click(function (){
        saveExamineMaintainer();
    });

    /*$("#assign-model").find("[name='engineerName']").blur(function (){
        engineerNameBlur(this);
    });*/

    $("#saveAssign").click(function (){
        checkSaveAssign();
    });

    $("#comple").click(function (){
        initCompleInit();
    });

    $("#saveComple").click(function (){
        saveComple();
    });

    $("#saveUpkeepData").click(function (){
        saveUpkeepData();
    });

    $("#event").click(function (){
        if(!$("input[name='one']:checked").length){
            flavrShowByTime("请选择一个保养", null, "danger", false);
            return;
        }

        $("#event-form").find("[name='upkeepId']").val($("input[name='one']:checked").val());
        var json = {keyType:1602,keyId:$("input[name='one']:checked").val(),type:"event",root:basePath};

        $("#saveEventDiv").eventData(json);
    });



    $("#part").click(function (){
        queryPartListByUpkeepId();
    });

    $("[name='addPart']").click(function (){
        $("#addPart-modal").iziModal("open",this);
    });

    $("#addPart").click(function (){
        checkAddPartInfo();
    });

    $("#savePart").click(function (){
        savePart();
    })


    $("#upkeepData").click(function (){
        if(!$("input[name='one']:checked").length){
            flavrShowByTime("请选择一个保养", null, "danger", false);
            return;
        }

        var status = $("input[name='one']:checked").parent().next().val();
        if(status == 1802 || status == 1806){

        }else{
            flavrShowByTime("当前保养记录不能补全信息", null, "danger", false);
            return;
        }

        $("#upkeep-data-form").find("[name='upkeepId']").val($("input[name='one']:checked").val());
            var url = basePath + "/upkeep/queryUpkeepInfo";
            publicAjax(url,"POST",{upkeepId:$("input[name='one']:checked").val()},function (data){
                var engineerId = data.data.engineerId;
                if(engineerId == null || engineerId == ""){
                        $("#engineer").show();
                }
                $("#upkeep-data-modal").iziModal("open",this);
            });
    });

    $("[name='is_dispatch']").on("ifChecked",function (){
            var value = $(this).val();
            if(value == 1){
                $("#dispatchDiv").show();
                validator();
            }else{
                $("#dispatchDiv").hide();
                $("#assignForm").data('bootstrapValidator').destroy();
            }
    });

    $("[name='hospital_user']").on("ifChecked",function (){
        var value = $(this).val();
        if(value == 1){
            $("#userDiv").show();
            ///validator();
        }else{
            $("#userDiv").hide();
            //$("#addUpkeepForm").data('bootstrapValidator').destroy();
        }
    });

    $("#assignServiceDiv").find("[name='serviceType']").on("ifChecked",function (){
        var value = $(this).val();
        $("#engineerDiv").show();
        $("#engineerDiv").find("[name='is_dispatch'][value='1']").iCheck("check");
        if(value == 1103){
            $("#assignMaintainerDiv").show();
            $("#assignSupplierDiv").hide();
            $("#assignManufacturerDiv").hide();
            $("#assignServiceDiv").find("[name='serviceId']").val(null);
            $("#engineerDiv").show();
            $("#engineerDiv").find("[name='is_dispatch'][value='1']").iCheck("check");
            $("#engineerDiv").find("[name='is_dispatch'][value='0']").parent().parent().hide();
        }else if(value == 1102){
            $("#assignManufacturerDiv").show();
            $("#assignMaintainerDiv").hide();
            $("#assignSupplierDiv").hide();
            var manufacturerId = $("#assignManufacturerDiv").find("[name='manufacturerId']").val();
            $("#assignServiceDiv").find("[name='serviceId']").val(manufacturerId);
            $("#engineerDiv").find("[name='is_dispatch'][value='0']").parent().parent().show();
        }else if(value == 1105){
            $("#assignManufacturerDiv").hide();
            $("#assignMaintainerDiv").hide();
            $("#assignSupplierDiv").show();
            var supplierId = $("#assignSupplierDiv").find("[name='supplierId']").val();
            $("#assignServiceDiv").find("[name='serviceId']").val(supplierId);
            $("#engineerDiv").find("[name='is_dispatch'][value='0']").parent().parent().show();
        }else{
            $("#assignManufacturerDiv").hide();
            $("#assignMaintainerDiv").hide();
            $("#assignSupplierDiv").hide();
            $("#assignServiceDiv").find("[name='serviceId']").val(null);
        }
    });


    $("#addPart-modal").find("[name='partExplain']").on("ifChecked",function (){
        var value = $(this).val();
        switch (value){
            case "2001":
                    $("#oldDiv").hide();
                    $("#newDiv").show();
                break;
            case "2000":
                $("#oldDiv").show();
                $("#newDiv").show();
                break;
            case "2002":
                $("#oldDiv").show();
                $("#newDiv").hide();
                break;
        }
    });

    $("#update").click(function (){
        updateEngineerInfoInit();
    });

    $("#saveEngineerInfo").click(function (){
        saveEngineerInfo();
    });

    $("#userDiv").find("[name='engineerName']").typeahead ({
        source: function (query, process) {
            var url = basePath + "/upkeep/queryPhoneByEngineerName";
            publicAjax(url,"POST",{keyword : query},function (data){
                if(data.ret == 200){
                    if(data.data == null ||data.data.length == 0 ){
                        return null;
                    }else{
                        var array = new Array();
                        $.each(data.data,function (index,item){
                            var name = item.engineerName  + " / " + item.mobile;
                            array.push({name:name,engineerName:item.engineerName,mobile:item.mobile});
                        });

                        return  process(array);
                    }
                }
            });
        },updater : function (item){
            //$("#userDiv").find("[name='engineerName']").val(item.engineerName);
            $("#userDiv").find("[name='mobile']").val(item.mobile);
            return this.$element.val().replace(new RegExp(this.query + '$'),'') + item.engineerName ;
        }
    });


    $("#dispatchDiv").find("[name='engineerName']").typeahead ({
        source: function (query, process) {
            var url = basePath + "/upkeep/queryPhoneByEngineerName";
            publicAjax(url,"POST",{keyword : query},function (data){
                if(data.ret == 200){
                    if(data.data == null ||data.data.length == 0 ){
                        return null;
                    }else{
                        var array = new Array();
                        $.each(data.data,function (index,item){
                            var name = item.engineerName  + " / " + item.mobile;
                            array.push({name:name,engineerName:item.engineerName,mobile:item.mobile});
                        });

                        return  process(array);
                    }
                }
            });
        },updater : function (item){
            //$("#userDiv").find("[name='engineerName']").val(item.engineerName);
            $("#dispatchDiv").find("[name='engineerPhone']").val(item.mobile);
            return this.$element.val().replace(new RegExp(this.query + '$'),'') + item.engineerName ;
        }
    });

}

function serviceTypeChange(){
    $("#addUpkeepForm").find("[name='serviceType']").on("ifChecked",function (){
        var value = $(this).val();
        if(value == 1103){
            $("#maintainerDiv").show();
            $("#supplierDiv").hide();
            $("#manufacturerDiv").hide();
            $("#addUpkeepForm").find("[name='serviceId']").val(null);
            $("#addUpkeepEngineerDiv").show();
        }else if(value == 1102){
            $("#manufacturerDiv").show();
            $("#maintainerDiv").hide();
            $("#supplierDiv").hide();
            var manufacturerId =  $("#manufacturerDiv").find("[name='manufacturerId']").val();
            $("#addUpkeepForm").find("[name='serviceId']").val(manufacturerId);
            $("#addUpkeepEngineerDiv").show();
        }else if(value == 1105){
            $("#manufacturerDiv").hide();
            $("#maintainerDiv").hide();
            $("#supplierDiv").show();
            var supplierId = $("#supplierDiv").find("[name='supplierId']").val();
            $("#addUpkeepForm").find("[name='serviceId']").val(supplierId);
            $("#addUpkeepEngineerDiv").show();
        }else{
            $("#manufacturerDiv").hide();
            $("#maintainerDiv").hide();
            $("#supplierDiv").hide();
            $("#addUpkeepForm").find("[name='serviceId']").val(null);
            $("#addUpkeepEngineerDiv").hide();
        }
    });

}

var  boolls= false;
function saveEngineerInfo(){
    $('#updateEngineer-form').bootstrapValidator('validate');
    if($('#updateEngineer-form').data('bootstrapValidator').isValid()){
        if(!boolls){
            boolls =true;
            var url = basePath + "/upkeep/updateEngineerNameAndEngineerPhone";
            publicAjax(url,"POST",$('#updateEngineer-form'),function (data){
                if(data.ret == 200){
                    flavrShowByTime(data.msg,null,"success",false);
                    boolls = false;
                    $("#updateEngineer").iziModal("close",this);
                    queryUpkeepList(0,10);
                }else{
                    flavrShowByTime(data.msg,null,"danger",false);
                    boolls = false;
                }
            });
        }
    }

}


function updateEngineerInfoInit(){
    if(!$("input[name='one']:checked").length){
        flavrShowByTime("请选择一个保养", null, "danger", false);
        return;
    }

    var status = $("input[name='one']:checked").parent().next().val();
    if(status == 1806 || status == 1802 || status == 1801){

    }else{
        flavrShowByTime("当前保养不能修改负责人", null, "danger", false);
        return;
    }

    var url = basePath + "/upkeep/queryUpkeepInfo";
    publicAjax(url,"POST",{upkeepId : $("input[name='one']:checked").val()},function (data){
        if(data.ret == 200){
            bindEngineerInfo(data.data.appointView);
        }else{
            flavrShowByTime(data.msg,null,"danger",false);
        }
    });
}

function bindEngineerInfo(obj){
    $("#updateEngineer-form").find("[name='appointId']").val(obj.appointId);
    $("#updateEngineer-form").find("[name='engineerName']").val(obj.engineerName == null ? '' : obj.engineerName);
    $("#updateEngineer-form").find("[name='engineerPhone']").val(obj.engineerPhone == null ? '' : obj.engineerPhone);
    $("#updateEngineer").iziModal("open",this);
}

function saveExamineMaintainer(){
    var url = basePath + "/upkeep/saveExamineMaintainer";
    publicAjax(url,"POST",$("#examine-maintainer-form"),function (data) {
        if(data.ret ==200){
            bindServiceInitData(data.data);
            $("#examine-maintainer").iziModal("close",this);
        }else{
            flavrShowByTime(data.msg,null,"danger",false);
        }
    })
}

/*

function engineerNameBlur(obj) {
    if($(obj).val().trim() == null || $(obj).val().trim() == ""){
        return;
    }

    var maintainerId = $("#assign-model").find("[name='maintainerId']").val();
    if(maintainerId == null || maintainerId == ""){
        flavrShowByTime("请选择服务商",null,"danger",false);
        return;
    }

    var json = {maintainerId:maintainerId,engineerName:$(obj).val().trim()}

    var url = basePath+"/upkeep/queryEngineerPhoneByName";
    publicAjax(url,"POST",json,function (data){
        if(data.ret == 200){
            $("#assign-model").find("[name='engineerPhone']").val(data.data == null ? '' : data.data);
        }
    });

}
*/

function assignServiceInit(){

    if(!$("input[name='one']:checked").length){
        flavrShowByTime("请选择一个保养", null, "danger", false);
        return;
    }

    var status = $("input[name='one']:checked").parent().next().val();
    if(status == 1800 || status == 1805){

    }else{
        flavrShowByTime("当前保养记录不能分配", null, "danger", false);
        return;
    }

    var json = {"upkeepId":$("input[name='one']:checked").val()};

    var url = basePath + "/upkeep/assignServiceInit";
    publicAjax(url,"POST",json,function (data){
        if(data.ret == 200){
            $("#assignForm").find("[name='upkeepId']").val($("input[name='one']:checked").val());
            bindServiceInitData(data.data);
        }else{
            flavrShowByTime(data.msg,null,"danger",false);
            return;
        }
    });
    $("#assign-model").iziModal("open",this);

}


function initCompleInit(){
    if(!$("input[name='one']:checked").length){
        flavrShowByTime("请选择一个保养", null, "danger", false);
        return;
    }
    var status = $("input[name='one']:checked").parent().next().val();
    if(status != 1803){
        flavrShowByTime("当前保养记录不能确认", null, "danger", false);
        return;
    }
    /*$("#compleForm").find("[name='upkeepId']").val($("input[name='one']:checked").val());
    $("#comple-modal").iziModal("open",this);*/
    $("#confirmDiv").confirmData({
        keyType:2902,
        keyId: $("input[name='one']:checked").val(),
        root: basePath+"/",
        confirmUrl: "upkeep/saveComple",
        typeStatus: 2,
        callback:function(obj){
            var isSuccess = obj.returnIsSuccess();
            if(isSuccess){
                flavrShowByTime("操作成功",null,"success",null);
                queryUpkeepList(0,$("#show-count").val());
            }else{
                flavrShowByTime("操作失败",null,"success",null);
            }
        }
    });
}

function bindServiceInitData(obj){
        $("#assignForm").find("[name='upkeepId']").val(obj.upkeepView.upkeepId);
        $("#createTimeSpan").html(obj.upkeepView.createTime == null ? '' : obj.upkeepView.createTime);
        $("#upkeepApplicantSpan").html(obj.upkeepView.upkeepApplicant == null ? '' : obj.upkeepView.upkeepApplicant);
        $("#upkeepApplicantPhoneSpan").html(obj.upkeepView.upkeepApplicantPhone == null ? '' : obj.upkeepView.upkeepApplicantPhone);

        $("#hospitalNameSpan").html(obj.hospitalName == null ? '' : obj.hospitalName);
        $("#deviceNameSpan").html(obj.deviceName == null ? '' : obj.deviceName);
        $("#deviceModelSpan").html(obj.deviceModel == null ? '' : obj.deviceModel);
        $("#snSpan").html(obj.sn == null ? '' : obj.sn);
        $("#enableTimeSpan").html(obj.enableTime == null ? '' : obj.enableTime);
        $("#lastUpkeepDateSpan").html(obj.lastUpkeepDate == null ? '' : obj.lastUpkeepDate);

        $("#manufacturerNameSpan").html(obj.manufacturerName == null ? '' : obj.manufacturerName);
        $("#manufacturerContactsSpan").html(obj.manufacturerContacts == null ? '' : obj.manufacturerContacts);
        $("#manufacturerPhoneSpan").html(obj.manufacturerPhone == null ? '' : obj.manufacturerPhone);

        $("#supplierNameSpan").html(obj.supplierName == null ? '' : obj.supplierName);
        $("#supplierContactsSpan").html(obj.supplierContacts == null ? '' : obj.supplierContacts);
        $("#supplierPhoneSpan").html(obj.supplierPhone == null ? '' : obj.supplierPhone);

        $("#maintainerNameSpan").html(obj.maintainerName == null ? '' : obj.maintainerName);
        $("#maintainerContactsSpan").html(obj.maintainerContacts == null ? '' : obj.maintainerContacts);
        $("#maintainerPhoneSpan").html(obj.maintainerPhone == null ? '' : obj.maintainerPhone);

        //绑定厂家维保的有效期
        var enableTime = obj.enableTime;
        var deviceWarrantyPeriod = obj. deviceWarrantyPeriod;
        if(enableTime == null || enableTime == "" || deviceWarrantyPeriod == null || deviceWarrantyPeriod == ""){
            $("#endManufacturerDateSpan").html("");
        }else{
            var array =  enableTime.split("-");
            var date = new Date(array[0],array[1],array[2]);
            var month = date.getMonth();
            month = month + deviceWarrantyPeriod;
            date.setMonth(month);
            var dateStr = date.getFullYear() + '-' + (date.getMonth()) + '-' + date.getDate();
            $("#endManufacturerDateSpan").html(dateStr);
        }
        //绑定供应商维保的有效期
        var supplierWarrantyPeriod = obj.supplierWarrantyPeriod;
        if(enableTime == null || enableTime == "" || supplierWarrantyPeriod == null || supplierWarrantyPeriod == ""){
            $("#endSupplierDateSpan").html("");
        }else{
            var array =  enableTime.split("-");
            var date = new Date(array[0],array[1],array[2]);
            var month = date.getMonth();
            month = month + supplierWarrantyPeriod;
            date.setMonth(month);
            var dateStr = date.getFullYear() + '-' + (date.getMonth()) + '-' + date.getDate();
            $("#endSupplierDateSpan").html(dateStr);
        }

        //绑定当前设备的维保情况
        switch (obj.devicePaoneAbroad){
            case 1103:
                $("#insideOutsideStrSpan").html("保外");
                break;
            case 1102:
                $("#insideOutsideStrSpan").html("厂商维保");
                break;
            case 1105:
                $("#insideOutsideStrSpan").html("经销商维保");
                break;
            default:$("#insideOutsideStrSpan").html("");
        }
        var serviceType = obj.upkeepView.serviceType;
        var serviceName = obj.upkeepView.serviceName == null ? '' :  obj.upkeepView.serviceName;
        var serviceContacts = obj.upkeepView.serviceContacts == null ? '' : obj.upkeepView.serviceContacts;
        var servicePhone =  obj.upkeepView.servicePhone  == null ?'' :  obj.upkeepView.servicePhone;
        $("#assignForm").find("[name='hospitalServiceType']").val(serviceType);
        switch (serviceType){
            case 1102:
                //厂商
                $("#serviceCompanySpan").html("医院选择的是厂商("+(serviceName)+")");
                break;
            case 1105:
                //供应商
                $("#serviceCompanySpan").html("医院选择的是经销商("+(serviceName)+")");
                break;
            case 1103:
                //维修商
                $("#serviceCompanySpan").html("医院选择的是维修商("+(serviceName)+")");
                //医院端选择的维修商需要审核。。。这里是添加审核按钮
                if(obj.upkeepView.serviceId == null && obj.upkeepView.examine == null){
                    var buttonHtml = "<button type='button' class='btn btn-info btn-sm' data-toggle='tooltip' onclick='bindServiceInfo(\""+obj.upkeepView.upkeepId+"\",\""+serviceName+"\",\""+serviceContacts+"\",\""+servicePhone+"\")'>审核</button>";
                    $("#serviceCompanySpan").append("&nbsp;&nbsp;").append(buttonHtml);
                }
                break;
            default :
                //无
                $("#serviceCompanySpan").html("医院没有选择服务商");
        }

        $("#serviceNameSpan").html(serviceContacts);
        $("#servicePhoneSpan").html(servicePhone);
        $("#assignServiceDiv").find("[name='serviceType'][value='"+obj.upkeepView.serviceType+"']").iCheck("check");
        $("#examineTr").html("");
        var examine = obj.upkeepView.examine;
        var examineComment = obj.upkeepView.examineComment == null ? '' : obj.upkeepView.examineComment;
        $("#assignForm").find("[name='examine']").val(examine);
        if(examine != null ){
            var html = "";
                if(examine == 1){
                    html = "<td class='text-muted' style='text-align: right'>审核结果：</td><td class='text-muted' style='text-align: left'>通过</td>"+
                    "<td class='text-muted' style='text-align: right'>审核说明：</td><td class='text-muted' style='text-align: left' colspan='3'>"+examineComment+"</td>";
                    $("[name='is_dispatch'][value='1']").iCheck("check");
                    $("#dispatchDiv").show();
                }else if(examine == 0){
                    html = "<td class='text-muted' style='text-align: right'>审核结果：</td><td class='text-muted' style='text-align: left'>不通过</td>"+
                        "<td class='text-muted' style='text-align: right'>审核说明：</td><td class='text-muted' style='text-align: left' colspan='3'>"+examineComment+"</td>";
                    $("#assignServiceDiv").show();
                }
            $("#examineTr").html(html);
        }

        $("#assignServiceDiv").find("[name='serviceId']").val(obj.upkeepView.serviceId);

        var flag = obj.flag;
        if(flag == 1){
            $("#assignServiceDiv").show();
            var url = basePath + "/repair/queryInfoPage";
            publicAjax(url,"POST",{deviceId:obj.upkeepView.deviceId},function (data){
                if(data.ret == 200){
                    if(data.data != null && data.data != ''){
                        if(data.data.manufacturer != null){
                            $("#assignManufacturerDiv").find("[name='manufacturerName']").val(data.data.manufacturer.manufacturerName);
                            $("#assignManufacturerDiv").find("[name='manufacturerId']").val(data.data.manufacturer.manufacturerId);
                            $("#assignManufacturerDiv").show();
                            $("#assignForm").find("[name='serviceType'][value='1102']").parent().parent().show();
                        }else{
                            $("#assignManufacturerDiv").hide();
                            $("#assignForm").find("[name='serviceType'][value='1102']").parent().parent().hide();
                        }
                        if(data.data.supplier != null){
                            $("#assignSupplierDiv").find("[name='supplierName']").val(data.data.supplier.supplierName);
                            $("#assignSupplierDiv").find("[name='supplierId']").val(data.data.supplier.supplierId);
                            $("#assignSupplierDiv").show();
                            $("#assignForm").find("[name='serviceType'][value='1105']").parent().parent().show();
                        }else{
                            $("#assignSupplierDiv").hide();
                            $("#assignForm").find("[name='serviceType'][value='1105']").parent().parent().hide();
                        }
                        $("#assignServiceDiv").find("[name='serviceType'][value='"+data.data.serviceType+"']").iCheck("check");
                        $("#engineerDiv").find("[name='is_dispatch'][value='1']").iCheck("check");
                        if(data.data.serviceType == 1103){
                            $("#assignMaintainerDiv").show();
                            $("#assignSupplierDiv").hide();
                            $("#assignManufacturerDiv").hide();
                            $("#engineerDiv").find("[name='is_dispatch'][value='0']").parent().parent().show();
                        }else if(data.data.serviceType == 1102){
                            $("#assignManufacturerDiv").show();
                            $("#assignMaintainerDiv").hide();
                            $("#assignSupplierDiv").hide();
                            $("#assignServiceDiv").find("[name='serviceId']").val(data.data.manufacturer.manufacturerId);
                            $("#engineerDiv").find("[name='is_dispatch'][value='0']").parent().parent().show();
                        }else if(data.data.serviceType == 1105){
                            $("#assignManufacturerDiv").hide();
                            $("#assignMaintainerDiv").hide();
                            $("#assignSupplierDiv").show();
                            $("#assignServiceDiv").find("[name='serviceId']").val(data.data.supplier.supplierId);
                            $("#engineerDiv").find("[name='is_dispatch'][value='0']").parent().parent().show();
                        }else{
                            $("#assignServiceDiv").find("[name='serviceType'][value='1103']").iCheck("check");
                            $("#assignForm").find("[name='serviceType'][value='1103']").iCheck("check")
                            $("#assignMaintainerDiv").show();
                            $("#assignManufacturerDiv").hide();
                            $("#assignSupplierDiv").hide();
                            $("#engineerDiv").find("[name='is_dispatch'][value='0']").parent().parent().hide();
                            $("#dispatchDiv").show();
                        }
                    }
                }else{
                    flavrShowByTime(data.msg,null,"danger",false);
                }
            });
        }else if(flag == 2){
                $("#assignServiceDiv").hide();
        }else if(flag == 3){
            $("#assignServiceDiv").hide();
        }


    //var engineerId = obj.upkeepView.engineerId;
    var engineerName = obj.upkeepView.engineerName;
    var mobile = obj.upkeepView.mobile;
    $("#engineerTr").html("");
    if((engineerName == null || engineerName == "") && (mobile == null || mobile == "")){
        $("#engineerTr").html("<td class='text-muted' style='text-align: right'>医院没有选择工程师</td><td colspan='6'>&nbsp;</td>");
        $("#engineerDiv").show();
        if(serviceType == 1103){
            $("#engineerDiv").find("[name='is_dispatch'][value='1']").iCheck("check");
            $("#engineerDiv").find("[name='is_dispatch'][value='0']").parent().parent().hide();
            $("#dispatchDiv").show();
        }
    }else{
        $("#engineerTr").html('<td class="text-muted " style="text-align: right">工程师姓名：</td>'+
            '<td class="text-muted " style="text-align: left">'+(obj.upkeepView.engineerName == null ? '' : obj.upkeepView.engineerName)+'</td>'+
            '<td class="text-muted " style="text-align: right">工程师电话：</td>'+
            '<td class="text-muted " style="text-align: left">'+(obj.upkeepView.mobile == null ? '' : obj.upkeepView.mobile)+'</td>'+
            '<td class="text-muted " style="text-align: right">&nbsp;</td>'+
            '<td class="text-muted " style="text-align: left">&nbsp;</td>');
            //$("#assignForm").find("[name='engineerId']").val(engineerId);
            $("#assignForm").find("[name='engineerName']").val(obj.upkeepView.engineerName);
            $("#assignForm").find("[name='engineerPhone']").val(obj.upkeepView.mobile);
            $("#engineerDiv").find("[name='is_dispatch']").val(1);
            $("#engineerDiv").hide();
        }
        $("#assignForm").find("[name='hospitalContacts']").val(obj.upkeepView.upkeepApplicant);
        $("#assignForm").find("[name='hospitalPhone']").val(obj.upkeepView.upkeepApplicantPhone);
}

function bindServiceInfo(upkeepId,serviceName,serviceContacts,servicePhone){
        $("#examine-maintainer-form").find("[name='maintainerName']").val(serviceName);
        $("#examine-maintainer-form").find("[name='maintainerContacts']").val(serviceContacts);
        $("#examine-maintainer-form").find("[name='maintainerPhone']").val(servicePhone);
        $("#examine-maintainer-form").find("[name='upkeepId']").val(upkeepId);
        $("#examine-maintainer").iziModal("open",this);

}

function upkeepInfo(id){
    location.href="<%=basePath%>/upkeep/info?id="+id;
}


//修改负责人信息
$("#updateEngineer").iziModal({
    title: "编辑负责人",
    headerColor: '#00c0ef',
    rtl: false,
    width: 600,
    zindex: 1044,
    focusInput: false,
    group: '',
    loop: false,
    history: false,
    overlayClose: false,
    autoOpen: false, // Boolean, Number
    bodyOverflow: true,
    onOpening: function () {
        updateEngineerValidator();
    },
    onOpened: function () {},
    onClosing: function () {
        $('#updateEngineer-form')[0].reset();
        $("#updateEngineer-form").data('bootstrapValidator').destroy();
    },
    onClosed: function () {}
});

// 审核维修商
$("#examine-maintainer").iziModal({
    title: "维修商信息",
    headerColor: '#00c0ef',
    rtl: false,
    width: 800,
    zindex: 1044,
    focusInput: false,
    group: '',
    loop: false,
    history: false,
    overlayClose: false,
    autoOpen: false, // Boolean, Number
    bodyOverflow: true,
    onOpening: function () {
    },
    onOpened: function () {},
    onClosing: function () {
        $('#examine-maintainer-form')[0].reset();
    },
    onClosed: function () {}
});


// 分配服务商Model
$("#assign-model").iziModal({
    title: "指派信息",
    headerColor: '#00c0ef',
    rtl: false,
    width: 1200,
    zindex: 1042,
    focusInput: false,
    group: '',
    loop: false,
    history: false,
    overlayClose: false,
    autoOpen: false, // Boolean, Number
    bodyOverflow: true,
    onOpening: function () {
    },
    onOpened: function () {},
    onClosing: function () {
        $("#assignForm").find("[name='upkeepId']").val("");
        $('#assignForm')[0].reset();
        if($("#assignForm").find("[name='is_dispatch']:checked").val() == 1){
            $("#assignForm").data('bootstrapValidator').destroy();
        }
    },
    onClosed: function () {}
});

$("#addUpkeep-modal").iziModal({
    title: "新增保养",
    headerColor: '#00c0ef',
    rtl: false,
    width: 600,
    zindex: 1042,
    focusInput: false,
    group: '',
    loop: false,
    history: false,
    overlayClose: false,
    autoOpen: false, // Boolean, Number
    bodyOverflow: true,
    onOpening: function () {
        validator10()
    },
    onOpened: function () {},
    onClosing: function () {
        $('#addUpkeepForm')[0].reset();
        $("#addUpkeepForm").data('bootstrapValidator').destroy();
        $("#addUpkeepForm").find("[name='deviceStatus']").val(null);
        $("#addUpkeepForm").find("[name='deviceStatus']").select2({
            language: 'zh-CN',
            placeholder: '请选择',
            allowClear: true});
    },
    onClosed: function () {}
});


// 确认保养完成
$("#comple-modal").iziModal({
    title: "确认保养",
    headerColor: '#00c0ef',
    rtl: false,
    width: 500,
    zindex: 1042,
    focusInput: false,
    group: '',
    loop: false,
    history: false,
    overlayClose: false,
    autoOpen: false, // Boolean, Number
    bodyOverflow: true,
    onOpening: function () {
    },
    onOpened: function () {},
    onClosing: function () {
        $("#compleForm").find("[name='upkeepId']").val("");
    },
    onClosed: function () {}
});


$("#upkeep-data-modal").iziModal({
    title: "补全保养信息",
    headerColor: '#00c0ef',
    rtl: false,
    width: 800,
    zindex: 1042,
    focusInput: false,
    group: '',
    loop: false,
    history: false,
    overlayClose: false,
    autoOpen: false, // Boolean, Number
    bodyOverflow: true,
    onOpening: function () {
        validator1();
    },
    onOpened: function () {},
    onClosing: function () {
        $('#upkeep-data-form')[0].reset();
        $("#upkeep-data-form").data('bootstrapValidator').destroy();
        $("#upkeep-data-form").find("[name='upkeepId']").val("");
    },
    onClosed: function () {}
});




$("#part-modal").iziModal({
    title: "备件列表",
    headerColor: '#00c0ef',
    width: 1200,
    zindex: 1043,
    autoOpen:false,
    focusInput: false,
    overlayClose: false,
    openFullscreen: false,
    onFullscreen: function(){},
    onResize: function(){},
    onOpening: function () {

    },
    onOpened: function () {},
    onClosing: function () {
        partMap = new Map();
    },
    onClosed: function () {}
});

$("#addPart-modal").iziModal({
    title: "新增备件",
    headerColor: "#00c0ef",
    overlayClose:true,
    autoOpen:false,
    history:false,
    zindex: 1044,
    width:1000,
    focusInput: false,
    bodyOverflow: true,
    fullscreen: true,
    openFullscreen: false,
    closeOnEscape: true,
    overlay: true,
    overlayClose: false,
    onOpening: function () {
        $("#oldFileForm input[name='keyType'],#newFileForm input[name='keyType']").val("1407");
        $("#oldFileForm input[name='fileType']").val("3404");
        $("#newFileForm input[name='fileType']").val("3403");
    },
    onOpened: function () {},
    onClosing: function () {
        //$('#addPartForm')[0].reset();
        clearAddPartForm();
        $("#oldFileForm")[0].reset();
        $("#newFileForm")[0].reset();
    },
    onClosed: function () {}
});

$("#showFileDiv").iziModal({
    title: "备件图片",
    headerColor: "#00c0ef",
    overlayClose:true,
    autoOpen:false,
    history:false,
    zindex: 9999,
    width:800,
    focusInput: false,
    bodyOverflow: true,
    fullscreen: true,
    openFullscreen: true,
    closeOnEscape: true,
    overlay: true,
    overlayClose: false,
    onOpening: function () {

    },
    onOpened: function () {},
    onClosing: function () {

    },
    onClosed: function () {}
});






function initElementCss(){
    $("#queryForm").find("[name='hospitalId']").val(null);
    $("#queryForm").find("[name='hospitalId']").select2({
        language: 'zh-CN',
        placeholder: '医院',

        allowClear: true});
    $("#queryForm").find("[name='status']").val(null);
    $("#queryForm").find("[name='status']").select2({
        language: 'zh-CN',
        placeholder: '状态',
        allowClear: true});
    $("#queryForm").find("[name='serviceId']").val(null);
    $("#queryForm").find("[name='serviceId']").select2({
        language: 'zh-CN',
        placeholder: '服务商',
        allowClear: true});

    $("#upkeep-data-form").find("[name=endDeviceStatus]").val(null);
    $("#upkeep-data-form").find("[name='endDeviceStatus']").select2({
        language: 'zh-CN',
        placeholder: '请选择',
        allowClear: true});

    $("#addUpkeepForm").find("[name=deviceStatus]").val(null);
    $("#addUpkeepForm").find("[name='deviceStatus']").select2({
        language: 'zh-CN',
        placeholder: '请选择',
        allowClear: true});


    $("#upkeep-data-form").find("input[name='upkeepEndTime']").datetimepicker({
        autoclose: true,
        todayHighlight: true,
        language: 'zh-CN',
        minuteStep:2,
        todayBtn: true
    }).on('hide',function(e) {
        $('#upkeep-data-form').data('bootstrapValidator')
            .updateStatus('upkeepEndTime', 'NOT_VALIDATED',null)
            .validateField('upkeepEndTime');
    });


   /* $("#addUpkeepForm").find("input[name='upkeepDate']").datetimepicker({
        autoclose: true,
        todayHighlight: true,
        language: 'zh-CN',
        minuteStep:1,
        todayBtn: true
    }).on('hide',function(e) {
        $('#addUpkeepForm').data('bootstrapValidator')
            .updateStatus('upkeepDate', 'NOT_VALIDATED',null)
            .validateField('upkeepDate');
    });*/




/*    $("#assignForm").find("input[name='dispathTime']").datetimepicker({
        autoclose: true,
        todayHighlight: true,
        language: 'zh-CN',
        minuteStep:1,
        todayBtn: true
    }).on('hide',function(e) {
        $('#assignForm').data('bootstrapValidator')
            .updateStatus('dispathTime', 'NOT_VALIDATED',null)
            .validateField('dispathTime');
    });*/

    $("input[type='radio'].flat-green").iCheck({
        checkboxClass: 'icheckbox_flat-green',
        radioClass: 'iradio_flat-green'
    });
}

function queryUpkeepList(start,end){
    var allName = $("#queryForm").find("[name='allName']").val();
    var hospitalId = $("#queryForm").find("[name='hospitalId']").val();
    var serviceId = $("#queryForm").find("[name='serviceId']").val();
    var status = $("#queryForm").find("[name='status']").val();
    var json = {start:start,end: $("#show-count").val(),allName:allName,hospitalId:hospitalId,serviceId:serviceId,status:status};
    var url = basePath+"/upkeep/queryUpkeepList"
    publicAjax(url,"POST",json,function (data) {
        if(data.ret == 200){
            bindUpkeepListData(data.data.list);
            $("#total-count").text(data.data.count);
        }else{
            flavrShowByTime(data.msg,null,"danger",false);
        }
    });
}

function bindUpkeepListData(obj){
    $("#upkeep_table").html("");
    if(obj == null || obj.length == 0){
        $("#upkeep_table").html("<tr><td class='text-center text-muted' colspan='15'>暂无保养数据</td></tr>");
        return;
    }else{
        var html = "";
        $.each(obj,function (index,item) {
            html+= "<tr><td class='text-center text-muted'>"+(index+1)+"</td>" +
                "<td class='text-center text-muted'><input type='checkbox' class='flat-green' name='one' value='"+item.upkeepId+"'><input type='hidden' value='"+item.status+"'></td>" +
                "<td class='text-center text-muted'><button type='button' class='btn btn-primary btn-xs' onclick='queryUpkeepInfo("+item.upkeepId+")' data-original-title='详情'><i class='fa fa-file-text-o'></i></button></td>" +
                "<td class='text-muted'>"+(item.deviceName == null ? '' : item.deviceName)+"</td>" +
                "<td class='text-muted'>"+(item.deviceModel == null ? '' : item.deviceModel)+"</td>" +
                "<td class='text-muted'>"+(item.sn == null ? '' : item.sn)+"</td>" +
                "<td class='text-muted'>"+(item.upkeepApplicant == null ? '' : item.upkeepApplicant)+"</td>" +
                "<td class='text-muted'>"+(item.upkeepApplicantPhone == null ? '' : item.upkeepApplicantPhone)+"</td>" +
                "<td class='text-muted'>"+(item.hospitalName == null ? '' : item.hospitalName)+"</td>" +
                "<td class='text-muted'>"+(item.hospitalServiceName == null ? '' : item.hospitalServiceName)+"</td>" +
                "<td class='text-muted'>"+(item.statusStr == null ? '' : item.statusStr)+"</td>" +
                "</tr>";
        });
        $("#upkeep_table").html(html);
    }
    initDomCss();
}



function initDomCss(){
    $('input[type="checkbox"].flat-green').iCheck({
        checkboxClass: 'icheckbox_flat-green',
        radioClass: 'iradio_flat-green'
    });

    $("input[name='one']").on('ifChecked', function(event){
        var current = $(this).parents("tr").index();
        $("[name='one']:checked").each(function(i){
            if($(this).parents("tr").index()!=current){
                $(this).iCheck('uncheck');
            }
        });
    });
}


function initQueryTerm(){
    var url = basePath+"/base/queryHosital";
    $("#queryForm").find("[name='hospitalId']").html("");
    publicAjax(url,"POST",{},function (data) {
        if(data.ret == 200){
            var html = "";
            $.each(data.data,function (index,item) {
                html += "<option value='"+item.hospitalId+"'>"+item.hospitalName+"</option>";
            });

            $("#queryForm").find("[name='hospitalId']").html(html);
            $("#queryForm").find("[name='hospitalId']").val(null);
        }else{
            flavrShowByTime(data.msg,null,"danger",false);
        }
    });

    $("#queryForm").find("[name='serviceId']").html("");
    url = basePath + "/base/queryMaintainer";
    publicAjax(url,"POST",{},function (data) {
        if(data.ret == 200){
            var html = "";
            $.each(data.data,function (index,item) {
                html += "<option value='"+item.maintainerId+"'>"+item.maintainerName+"</option>";
            });
            $("#queryForm").find("[name='serviceId']").html(html);
            $("#queryForm").find("[name='serviceId']").val(null);
        }else{
            flavrShowByTime(data.msg,null,"danger",false);
        }
    });

    $("#queryForm").find("[name='status']").html("");
    url = basePath + "/base/queryItem";
    publicAjax(url,"POST",{type:'upkeep_status'},function (data) {
        if(data.ret == 200){
            var html = "";
            $.each(data.data,function (index,item) {
                html += "<option value='"+item.itemId+"'>"+item.item+"</option>";
            });
            $("#queryForm").find("[name='status']").html(html);
            $("#queryForm").find("[name='status']").val(null);
        }else{
            flavrShowByTime(data.msg,null,"danger",false);
        }
    });
}


function queryUpkeepInfo(id){
    var url = basePath+"/upkeep/info?upkeepId="+id;
    location.href = url;
}

function updateEngineerValidator(){
    $('#updateEngineer-form').bootstrapValidator({
        excluded: [':disabled', ':hidden', ':not(:visible)'],
        live: 'enabled',
        message: '非有效值',
        fields: {
            engineerName: {
                validators: {
                    notEmpty: {
                        message: '不能为空'
                    }
                }
            },engineerPhone:{
                validators: {
                    notEmpty: {
                        message: '不能为空'
                    },
                    regexp: {
                        regexp: /^1[3|4|5|7|8][0-9]\d{8}$/,
                        message: '请填写正确的手机号码'
                    }
                }
            }
        }
    });
}

function validator10(){
    $('#addUpkeepForm').bootstrapValidator({
        excluded: [':disabled', ':hidden', ':not(:visible)'],
        live: 'enabled',
        message: '非有效值',
        fields: {
            deviceStatus: {
                validators: {
                    notEmpty: {
                        message: '不能为空'
                    }
                }
            },upkeepApplicant: {
                validators: {
                    notEmpty: {
                        message: '不能为空'
                    }
                }
            },upkeepApplicantPhone:{
                validators: {
                    notEmpty: {
                        message: '不能为空'
                    },
                    regexp: {
                        regexp: /^1[3|4|5|7|8][0-9]\d{8}$/,
                        message: '请填写正确的手机号码'
                    }
                }
            }
        }
    });
}

function validator(){
    $('#assignForm').bootstrapValidator({
        excluded: [':disabled', ':hidden', ':not(:visible)'],
        live: 'enabled',
        message: '非有效值',
        fields: {
            engineerPhone: {
                validators: {
                    regexp: {
                        regexp: /^1[3|4|5|7|8][0-9]\d{8}$/,
                        message: '请填写正确的手机号码'
                    }
                }
            },maintainerId:{
                validators: {
                    notEmpty: {
                        message: '不能为空'
                    }
                }
            },hospitalPhone:{
                validators: {
                    notEmpty: {
                        message: '不能为空'
                    },
                    regexp: {
                        regexp: /^1[3|4|5|7|8][0-9]\d{8}$/,
                        message: '请填写正确的手机号码'
                    }
                }
            }
            /*,dispathTime:{
                validators: {
                    notEmpty: {
                        message: '不能为空'
                    }
                }
            }*/
        }
    });
}



function validator1(){
    $('#upkeep-data-form').bootstrapValidator({
        excluded: [':disabled', ':hidden', ':not(:visible)'],
        live: 'enabled',
        message: '非有效值',
        fields: {
            travelTime: {
                validators: {
                    regexp: {
                        regexp:  /^[0-9]\d*(\.\d{1})?$/,
                        message: '请输入正确的差旅时间'
                    }
                }
            }
        }
    });
}

function checkSaveAssign(){
    var reg = /^1[3|4|5|7|8][0-9]\d{8}$/;
    var serviceType = $("#assignServiceDiv").find("[name='serviceType']:checked").val();
    var is_dispatch =  $("[name='is_dispatch']:checked").val();
    var engineerId = $("#assignForm").find("[name='engineerId']").val();

    var hospitalServiceType = $("#assignForm").find("[name='hospitalServiceType']").val();//判断医院端是否有选择服务商
    var  examine = $("#assignForm").find("[name='examine']").val();
    var serviceId = $("#assignForm").find("[name='serviceId']").val();
    if((serviceId == null || serviceId == "") && hospitalServiceType == 1103 && (examine == null || examine == "")){
        flavrShowByTime("请审核服务商信息",null,"danger",false);
        return;
    }else{
        if(((serviceId == null || serviceId=="") || hospitalServiceType == "") && serviceType == 1103){
            var serviceName = $("#assignForm").find("[name='serviceName']").val();
            if(serviceName == null || serviceName == ""){
                flavrShowByTime("请填写维修商名称",null,"danger",false);
                return;
            }

            var serviceContacts = $("#assignForm").find("[name='serviceContacts']").val();
            if(serviceContacts == null || serviceContacts == ""){
                flavrShowByTime("请填写维修商联系人",null,"danger",false);
                return;
            }

            var servicePhone = $("#assignForm").find("[name='servicePhone']").val();
            if(servicePhone == null || servicePhone == ""){
                flavrShowByTime("请填写维修商联系电话",null,"danger",false);
                return;
            }else{
                if(!reg.test(servicePhone)){
                    flavrShowByTime("请填写正确的维修商联系电话",null,"danger",false);
                    return;
                }
            }
        }

    }

    if((serviceType == 1103 || is_dispatch == 1) && (engineerId == null || engineerId == '')){
       /* var dispathTime =$("#assignForm").find("[name='dispathTime']").val();
        if(dispathTime == null || dispathTime == ""){
            flavrShowByTime("请填写派工时间",null,"danger",false);
            return;
        }*/

        var engineerName = $("#assignForm").find("[name='engineerName']").val();
        if(engineerName == null || engineerName == ""){
            flavrShowByTime("请填写负责人姓名",null,"danger",false);
            return;
        }

        var engineerPhone = $("#assignForm").find("[name='engineerPhone']").val();
        if(engineerPhone == null || engineerPhone == ""){
            flavrShowByTime("请填写负责人电话",null,"danger",false);
            return;
        }else{
            if(!reg.test(engineerPhone)){
                flavrShowByTime("请填写正确的负责人电话号码",null,"danger",false);
                return;
            }
        }

        var hospitalContacts = $("#assignForm").find("[name='hospitalContacts']").val();
        if(hospitalContacts == null || hospitalContacts == ""){
            flavrShowByTime("请填写医院联系人",null,"danger",false);
            return;
        }

        var hospitalPhone = $("#assignForm").find("[name='hospitalPhone']").val();
        if(hospitalPhone == null || hospitalPhone == ""){
            flavrShowByTime("请填写医院联系人电话",null,"danger",false);
            return;
        }else {
            if(!reg.test(hospitalPhone)){
                flavrShowByTime("请填写正确的医院联系人电话",null,"danger",false);
                    return;
            }
        }
    }

    saveAssign();
}

var bool = false;
function saveAssign(){
    $('#assignForm').bootstrapValidator('validate');
    if($('#assignForm').data('bootstrapValidator').isValid()){
        /*if($("#assignForm").find("[name='engineerPhone']").val() == null || $("#assignForm").find("[name='engineerPhone']").val() == ""){
            flavrShowByTime("工程师电话号码不能为空",null,"danger",false);
            return;
        }*/
        if(!bool){
            bool = true;
            var url = basePath+"/upkeep/saveAssign";
            publicAjax(url,"POST",$('#assignForm'),function (data) {
                if(data.ret == 200){
                    bool = false;
                    flavrShowByTime(data.msg,null,"success",false);
                    $("#assign-model").iziModal("close",this);
                    queryUpkeepList(0,10);
                }else{
                    bool = false;
                    flavrShowByTime(data.msg,null,"danger",false);

                }
            });
        }
    }
}

var bools = false;
function saveComple(){
    var url = basePath+"/upkeep/saveComple";
    var upkeepId = $("#compleForm").find("[name='upkeepId']").val();
    var comment =$("#compleForm").find("[name='comment']").val();
    if(!bools){
        bools = true;
        publicAjax(url,"POST",{upkeepId:upkeepId,comment:comment},function (data){
            if(data.ret == 200){
                flavrShowByTime(data.msg,null,"success",false);
                $("#comple-modal").iziModal("close",this);
                queryUpkeepList(0,10);
            }else{
                flavrShowByTime(data.msg,null,"danger",false);
            }
            bools =false;
        })
    }
}

var bools = false;
function saveUpkeepData() {
    $('#upkeep-data-form').bootstrapValidator('validate');
    if($('#upkeep-data-form').data('bootstrapValidator').isValid()){
        var travelTime= $("#upkeep-data-form").find("[name='travelTime']").val();
        if(travelTime != null && travelTime != ''){
            $("#upkeep-data-form").find("[name='travelTime']").val(travelTime*10);
        }
        if(!bools){
            bools = true;
            isFileUpload($("#upkeep-data-form"),function (data){
                $("#upkeep-data-form").find("[name='fileList']").val(JSON.stringify(data));
                var url=basePath+"/upkeep/saveUpkeepData";
                publicAjax(url,"POST",$("#upkeep-data-form"),function (data){
                    if(data.ret == 200){
                        flavrShowByTime(data.msg,null,"success",false);
                        $("#upkeep-data-modal").iziModal("close",this);
                        queryUpkeepList(0,10);
                    }else{
                        flavrShowByTime(data.msg,null,"danger",false);
                        $("#upkeep-data-form").find("[name='travelTime']").val(travelTime/10);
                    }
                    bools =false;
                });
            });
        }
    }
}






function queryPartListByUpkeepId(){
    if(!$("input[name='one']:checked").length){
        flavrShowByTime("请选择一个保养", null, "danger", false);
        return;
    }
    var upkeepId = $("input[name='one']:checked").val();
    $("#part-modal").find("[name='upkeepId']").val(upkeepId);
    var url = basePath+"/base/queryPartList";
    publicAjax(url,"POST",{keyId:upkeepId,keyType:1900},function (data){
            if(data.ret == 200){
                bindPartListData(data.data);
            }else{
                flavrShowByTime(data.msg,null,"danger",false);
            }
    });

}

var partMap = new Map();
function bindPartListData(obj){
    var str =  "";
    if(obj == null || obj.length == 0){
        str = "<tr><td class='text-muted text-center' colspan='15'>暂无数据</td></tr>";
    }else{
        $.each(obj,function (index,item){
            var oldFileLength = item.oldFileList == null ? 0 : item.oldFileList.length;
            var newFileLength = item.newFileList == null ? 0 : item.newFileList.length;
            str+= "<tr>" +
                "<td class='ext-muted text-center'><button type='button' class='btn btn-danger btn-xs' data-toggle='tooltip' title='删除' onclick='deletePart("+item.partId+",this)'><i class='fa fa-times'></i></button></td>" +
                "<td class='ext-muted text-center'>"+(item.partExplainName== null ? '':item.partExplainName )+"</td>" +
                "<td class='ext-muted text-center'>"+(item.oldPartName== null ? '':item.oldPartName )+"</td>" +
                "<td class='ext-muted text-center'>"+(item.oldPartBrand== null ? '':item.oldPartBrand )+"</td>" +
                "<td class='ext-muted text-center'>"+(item.oldPartModel== null ? '':item.oldPartModel )+"</td>" +
                "<td class='ext-muted text-center'>"+(item.oldPartSn== null ? '':item.oldPartSn )+"</td>" +
                "<td class='ext-muted text-center'>"+(item.oldPartPrice== null ? '':item.oldPartPrice/100 )+"</td>" +
                "<td class='ext-muted text-center'>"+(item.newPartName== null ? '':item.newPartName )+"</td>" +
                "<td class='ext-muted text-center'>"+(item.newPartBrand== null ? '':item.newPartBrand )+"</td>" +
                "<td class='ext-muted text-center'>"+(item.newPartModel== null ? '':item.newPartModel )+"</td>" +
                "<td class='ext-muted text-center'>"+(item.newPartSn== null ? '':item.newPartSn )+"</td>" +
                "<td class='ext-muted text-center'>"+(item.newPartPrice== null ? '':item.newPartPrice/100 )+"</td>" +
                "<td class='ext-muted text-center'><a href='javascript:showPartFile("+item.partId+",1)'>"+oldFileLength+"</a></td>" +
                "<td class='ext-muted text-center'><a href='javascript:showPartFile("+item.partId+",2)'>"+newFileLength+"</a></td>" +
                "<td class='ext-muted text-center'>"+(item.remark== null ? '':item.remark )+"</td>" +

                "</tr>";
            item.flag = 2;  //操作：1是新增，2是修改(暂时不提供修改功能)，3是删除
            partMap.put(item.partId,item);
        });
    }
    $("#part_list").html(str);
    $("#part-modal").iziModal("open",this);
}

function deletePart(id,obj){
        if(partMap.get(id).partId != null && partMap.get(id).partId != ""){
            partMap.get(id).flag = 3;
        }else{
            partMap.remove(id);
        }
        $(obj).parent().parent().remove();
}

var  count = 0;

function checkAddPartInfo(){
    var reg = /^[0-9]\d*(\.\d{1,2})?$/;
    var oldPartPrice = $("#addPart-modal").find("[name='oldPartPrice']").val();
    if(oldPartPrice != null && oldPartPrice != ''){
        if(!reg.test(oldPartPrice)){
            flavrShowByTime("请输入正确格式的旧备件价格。",null,"danger",false);
            return;
        }else{
            oldPartPrice = oldPartPrice *100;
        }
    }
    var newPartPrice = $("#addPart-modal").find("[name='newPartPrice']").val();
    if(newPartPrice != null && newPartPrice != ''){
        if(!reg.test(newPartPrice)){
            flavrShowByTime("请输入正确格式的新备件价格。",null,"danger",false);
            return;
        }else{
            newPartPrice = newPartPrice *100;
        }
    }

    /*isFileUpload($("#oldFileForms"),function (fileList){
        var oldFileList = null;
        var newFileList = null;
        isFileUpload($("#newFileForm"),function (fileLists){
            if(fileLists != null && fileLists.length>0){
                newFileList = fileLists;
            }
            if(fileList != null && fileList.length>0){
                oldFileList = fileList;
            }
            addPartInfo(oldPartPrice,newPartPrice,oldFileList,newFileList);
        });
    });*/


    isFileUpload($("#newFileForm"),function (fileLists){
        var oldFileList = null;
        var newFileList = null;
        isFileUpload($("#oldFileForm"),function (fileList){
            if(fileLists != null && fileLists.length>0){
                newFileList = fileLists;
            }
            if(fileList != null && fileList.length>0){
                oldFileList = fileList;
            }
            addPartInfo(oldPartPrice,newPartPrice,oldFileList,newFileList);
        });
    });


}

function addPartInfo(oldPartPrice,newPartPrice,oldFileList,newFileList){
        var item = {};
        var oldPartName = $("#addPart-modal").find("[name='oldPartName']").val();
        var oldPartBrand = $("#addPart-modal").find("[name='oldPartBrand']").val();
        var oldPartModel = $("#addPart-modal").find("[name='oldPartModel']").val();
        var oldPartSn = $("#addPart-modal").find("[name='oldPartSn']").val();
        var newPartName = $("#addPart-modal").find("[name='newPartName']").val();
        var newPartBrand = $("#addPart-modal").find("[name='newPartBrand']").val();
        var newPartModel = $("#addPart-modal").find("[name='newPartModel']").val();
        var newPartSn = $("#addPart-modal").find("[name='newPartSn']").val();
        var remark = $("#addPart-modal").find("[name='remark']").val();
        var  partExplain = $('input[name="partExplain"]:checked').val();
        var partExplainName = "";
        if(partExplain == 2001){
            partExplainName = "新增";
        }else if(partExplain == 2000){
            partExplainName = "更换";
        }else if(partExplain == 2002){
            partExplainName = "收回";
        }

        if(partExplain == 2001 || partExplain == 2000){
            item.newPartName = newPartName;
            item.newPartBrand = newPartBrand;
            item.newPartModel = newPartModel;
            item.newPartSn = newPartSn;
            item.newPartPrice = newPartPrice;
            item.newFileList = newFileList;
        }
        if(partExplain == 2002 || partExplain == 2000){
            item.oldPartName = oldPartName;
            item.oldPartBrand = oldPartBrand;
            item.oldPartModel = oldPartModel;
            item.oldPartSn = oldPartSn;
            item.oldPartPrice = oldPartPrice;
            item.oldFileList = oldFileList;
        }
        item.remark = remark;
        item.flag = 1;
        item.partExplain = partExplain;
        item.partExplainName = partExplainName;
        partMap.put(count,item);
        showaddPart(item,count);
        count++;
}


function showaddPart(item,index){
    var oldFileLength = item.oldFileList == null ? 0: item.oldFileList.length;
    var newFileLength = item.newFileList == null ? 0: item.newFileList.length;

   var str = "<tr>" +
       "<td class='ext-muted text-center'><button type='button' class='btn btn-danger btn-xs' data-toggle='tooltip' title='删除' onclick='deletePart("+index+",this)'><i class='fa fa-times'></i></button></td>" +
        "<td class='ext-muted text-center'>"+(item.partExplainName== null ? '':item.partExplainName )+"</td>" +
        "<td class='ext-muted text-center'>"+(item.oldPartName== null ? '':item.oldPartName )+"</td>" +
        "<td class='ext-muted text-center'>"+(item.oldPartBrand== null ? '':item.oldPartBrand )+"</td>" +
        "<td class='ext-muted text-center'>"+(item.oldPartModel== null ? '':item.oldPartModel )+"</td>" +
        "<td class='ext-muted text-center'>"+(item.oldPartSn== null ? '':item.oldPartSn )+"</td>" +
        "<td class='ext-muted text-center'>"+(item.oldPartPrice== null ? '':item.oldPartPrice /100)+"</td>" +
        "<td class='ext-muted text-center'>"+(item.newPartName== null ? '':item.newPartName )+"</td>" +
        "<td class='ext-muted text-center'>"+(item.newPartBrand== null ? '':item.newPartBrand )+"</td>" +
        "<td class='ext-muted text-center'>"+(item.newPartModel== null ? '':item.newPartModel )+"</td>" +
        "<td class='ext-muted text-center'>"+(item.newPartSn== null ? '':item.newPartSn )+"</td>" +
        "<td class='ext-muted text-center'>"+(item.newPartPrice== null ? '':item.newPartPrice /100)+"</td>" +
        "<td class='ext-muted text-center'><a href='javascript:showPartFile("+index+",1)'>"+oldFileLength+"</a></td>" +
        "<td class='ext-muted text-center'><a href='javascript:showPartFile("+index+",2)'>"+newFileLength+"</a></td>" +
        "<td class='ext-muted text-center'>"+(item.remark== null ? '':item.remark )+"</td>" +
        "</tr>";
    if(partMap.size() == 1){
        $("#part_list").html(str);
    }else{
        $("#part_list").append(str);
    }

    $("#addPart-modal").iziModal("close",this);
}

function showPartFile(id,type){
    $("#oldFileImgDiv").html("");
    $("#newFileImgDiv").html("");
    var fileList;
    if(type == 1){
        fileList = partMap.get(id).oldFileList;
    }else{
        fileList = partMap.get(id).newFileList;
    }
    if(fileList == null){
        return;
    }else{
        $.each(fileList,function (index,item){
            if(type == 1){
                $("#oldFileImgDiv").append("<img style='width:45%' height='400px;' src='"+item.fileUrl+"'/>");
                $("#newFileDiv").hide();
                $("#oldFileDiv").show();
            }else{
                $("#newFileImgDiv").append("<img style='width:45%' height='400px;' src='"+item.fileUrl+"'/>");
                $("#oldFileDiv").hide();
                $("#newFileDiv").show();
            }
        });
    }

    $("#showFileDiv").find("img").viewer("destroy");
    $("#showFileDiv").find("img").viewer();

    $("#showFileDiv").iziModal("open",this);
}

function clearAddPartForm(){
    $("#addPart-modal").find("[name='oldPartName']").val("");
    $("#addPart-modal").find("[name='oldPartBrand']").val("");
    $("#addPart-modal").find("[name='oldPartModel']").val("");
    $("#addPart-modal").find("[name='oldPartPrice']").val("");
    $("#addPart-modal").find("[name='oldPartSn']").val("");
    $("#addPart-modal").find("[name='files']").val("");
    $("#addPart-modal").find("[name='newPartName']").val("");
    $("#addPart-modal").find("[name='newPartBrand']").val("");
    $("#addPart-modal").find("[name='newPartModel']").val("");
    $("#addPart-modal").find("[name='newPartSn']").val("");
    $("#addPart-modal").find("[name='newPartPrice']").val("");
    $("#addPart-modal").find("[name='remark']").val("");
}

function savePart(){
       var keyId =  $("#part-modal").find("[name='upkeepId']").val();
        console.log(JSON.stringify(partMap));
        if(partMap.size()  ==  0){
            $("#part-modal").iziModal("close",this);
            return;
        }else{
            var array = new Array();
            partMap.each(function (key,value,index) {
                array.push(value);
            })
            var partList = JSON.stringify(array);
            var url = basePath+"/part/savePartByBatch";
            var json = {};
            json.partList = partList;
            json.keyId = keyId;
            json.keyType = 1900;
            publicAjax(url,"POST",json,function (data){
                if(data.ret == 200){
                    flavrShowByTime(data.msg,null,"success",false);
                    $("#part-modal").iziModal("close",this);
                }else{
                    flavrShowByTime(data.msg,null,"danger",false);
                }
            });
        }
}

var addbool = false;
function saveUpkeep(){
    $('#addUpkeepForm').bootstrapValidator('validate');
    if($('#addUpkeepForm').data('bootstrapValidator').isValid()){

        var deviceId  = $("#addUpkeepForm").find("[name='deviceId']").val();
        var hospitalId  = $("#addUpkeepForm").find("[name='hospitalId']").val();



        if(deviceId == null || deviceId =="" ){
            flavrShowByTime("请选择一个设备保养",null,"danger",false);
            return;
        }
        var hospital_user = $('input[name="hospital_user"]:checked').val();
        if(userType == 1104){
            if(hospitalId == null || hospitalId =="" ){
                flavrShowByTime("请选择医院",null,"danger",false);
                return;
            }
        }

        if(hospital_user == 1){
                var engineerName = $("#addUpkeepForm").find("[name='engineerName']").val();
                var mobile = $("#addUpkeepForm").find("[name='mobile']").val();
                if(engineerName == null || engineerName == ""){
                    flavrShowByTime("请填写工程师姓名",null,"danger",false);
                    return;
                }
            if(mobile == null || mobile == ""){
                flavrShowByTime("请填写工程师电话",null,"danger",false);
                return;
            }else{
                var reg = /^1[3|4|5|7|8][0-9]\d{8}$/;
                if(!reg.test(mobile)){
                    flavrShowByTime("请填写正确的电话号码",null,"danger",false);
                    return;
                }
            }
        }else{
            $("#dispatchDiv").find("input[type ='text']").val("");
        }

        if(!addbool){
            addbool = true;
            var url = basePath+"/upkeep/addUpkeep";
            publicAjax(url,"POST",$("#addUpkeepForm"),function (data){
                if(data.ret == 200){
                    addbool=false;
                    queryUpkeepList(0,10);
                    flavrShowByTime(data.msg,null,"success",false);
                    $("#addUpkeep-modal").iziModal("close",this);
                   /* if(userType == 1104){
                        isAssign(data);
                    }else{
                        flavrShowByTime(data.msg,null,"success",false);
                        $("#addUpkeep-modal").iziModal("close",this);
                    }*/
                }else{
                    addbool=false;
                    flavrShowByTime(data.msg,null,"danger",false);
                }
            })
        }
    }
}

//设备保养提示。。是否在保养中。
function deviceUpkeepPrompt(msg){
    new $.flavr({
        closeOverlay : true,
        closeEsc : true,
        content : msg+",是否申请保养",
        buttons:[
            {text:'取消',style:'info',action:function(){
                $("#addUpkeep-modal").iziModal("close",this);
            }},
            {
                text:'确定',
                style:'primary',
                action:function(){

                }
            }
        ]
    });
}


function isAssign(data){
    new $.flavr({
        closeOverlay : true,
        closeEsc : true,
        content : data.msg +'，是否分配服务商？',
        buttons:[
            {text:'以后再说',style:'info',action:function(){
                $("#addUpkeep-modal").iziModal("close",this);
            }},
            {
                text:'立即分配',
                style:'primary',
                action:function(){
                    $("[name='one'][value='"+data.data+"']").iCheck("check");
                    $("#addUpkeep-modal").iziModal("close",this);
                    assignServiceInit();
                }
            }
        ]
    });
}


$('input[name=files]').fileinput({
    language: 'zh', //设置语言
    enctype: 'multipart/form-data',
    showUpload: false, //是否显示上传按钮
    showCaption: false,//是否显示标题
    browseClass: "btn btn-info", //按钮样式
    msgFilesTooMany: "选择上传的文件数量({n}) 超过允许的最大数值{m}！"
});

